#!/bin/bash

# 定义函数，实现 SM4 加密
function sm4_encrypt() {
  read -p "请输入需要加密的字符串: " plaintext
  read -p "请输入密钥: " key
  ciphertext=$(echo -n "$plaintext" | /opt/tongsuo/bin/tongsuo enc -sm4-cbc -K "$key" -iv "1fb2d42fb36e2e88a220b04f2e49aa13" -nosalt -base64)
  echo "加密结果：$ciphertext"
}

# 定义函数，实现 SM4 解密
function sm4_decrypt() {
  read -p "请输入需要解密的密文: " ciphertext
  read -p "请输入密钥: " key
  plaintext=$(echo $ciphertext | /opt/tongsuo/bin/tongsuo enc -d -sm4-cbc -K "$key" -iv "1fb2d42fb36e2e88a220b04f2e49aa13" -nosalt -base64)
  echo "解密结果：$plaintext"
}

# 定义函数，实现 SM3 杂凑算法
function sm3_hash() {
  read -p "请输入需要加密的字符串: " plaintext
  hash=$(echo -n "$plaintext" | /opt/tongsuo/bin/tongsuo dgst -sm3)
  echo "哈希结果：$hash"
}

# 定义函数，实现 SM2 签名
function sm2_sign() {
  read -p "请输入需要签名的文件地址: " file
  signature=$(/opt/tongsuo/bin/tongsuo dgst -sm3 -sign sm2.key -out signature.bin "$file")
  echo "签名结果已保存到 signature.bin"
}

# 定义函数，实现 SM2 验签
function sm2_verify() {
  read -p "请输入源文件地址: " file
  read -p "请输入签名文件地址: " signature_file
  /opt/tongsuo/bin/tongsuo dgst -sm3 -verify sm2pub.key -signature "$signature_file" "$file"
  if [ $? -eq 0 ]; then
    echo "验签成功"
  else
    echo "验签失败"
  fi
}

# 主程序
echo "欢迎使用 SM 加密工具"
echo "请选择功能："
echo "1. SM4 加密解密"
echo "2. SM3 杂凑算法"
echo "3. SM2 签名和验签"
read -p "请输入选项（1-3）: " choice

case $choice in
  1)
    echo "请选择操作："
    echo "1. SM4 加密"
    echo "2. SM4 解密"
    read -p "请输入选项（1-2）: " sub_choice
    case $sub_choice in
      1)
        sm4_encrypt
        ;;
      2)
        sm4_decrypt
        ;;
      *)
        echo "无效选项"
        ;;
    esac
    ;;
  2)
    sm3_hash
    ;;
  3)
    echo "请选择操作："
    echo "1. SM2 签名"
    echo "2. SM2 验签"
    read -p "请输入选项（1-2）: " sub_choice
    case $sub_choice in
      1)
        sm2_sign
        ;;
      2)
        sm2_verify
        ;;
      *)
        echo "无效选项"
        ;;
    esac
    ;;
  *)
    echo "无效选项"
    ;;
esac